package com.flower.hooc.app.api.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.flower.hooc.bean.pojo.entity.Order;
import com.flower.hooc.bean.pojo.vo.RespResult;
import com.flower.hooc.service.OrderService;
import com.flower.hooc.util.configurations.AlipayConfig;
import com.flower.hooc.util.constants.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author:kevinfoo
 * @date:2020/09/01
 * @file:com.flower.controller
 */
@CrossOrigin
@RestController
@RequestMapping("/hooc/order")
@Api(tags = "订单业务接口")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @CrossOrigin
    @RequestMapping(value = "/start", method = RequestMethod.GET)
    @ApiOperation("购买跳转支付宝")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "WIDout_trade_no", value = "订单编号", required = true,
                    dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "WIDtotal_amount", value = "订单金额", required = true,
                    dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "WIDsubject", value = "订单subject", required = true,
                    dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "WIDbody", value = "订单body", required = true,
                    dataType = "String", paramType = "query")
    })
    public String startOrder(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("/order/start begin");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");
        //公共参数
        String commonParams = new String(request.getParameter("passback_params").getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("/order/start trade_no is : " + out_trade_no);
        System.out.println("/order/start price is : " + total_amount);
        System.out.println("/order/start subject is : " + subject);
        System.out.println("/order/start param is : " + commonParams);

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"passback_params\":\"" + commonParams + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        System.out.println("alipayRequest is : " + alipayRequest);
        System.out.println("result is : " + result);

        response.setContentType("text/html;charset=gbk");
        PrintWriter out = response.getWriter();
        out.print(result);
        return null;
    }

    @RequestMapping(value = "/returnOrder", method = RequestMethod.GET)
    @ApiOperation("支付成功回调")
    public String returnOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*1.获取各种参数，
         * http://ji33954155.qicp.vip/hooc/order/returnOrder?
         * charset=utf-8
         * &out_trade_no=202093161038994
         * &method=alipay.trade.page.pay.return
         * &total_amount=831.00
         * &sign=G3XUPNT8zwOzlzOlF7nmEEmBcqCX1ukwM83%2F4wbd3PHSJM9e3pLICqF1agEY1tsGQKUu%2B6NK4xFZGwNVTEPT%2FTYKFx22ddhl69%2BJe8IA%2Fj2Ks0H9UWtlwj6joDp3Cj2rxEekFfMmr4bkvgsUudhgj9z19sVpiAKISN%2Fs3lPKxv6W2N9kSahjaXzlRkWda5xiM3MCQlw9GBh88IDwHnQ92tZ%2BAXje%2FyvrAi8NWSbEjoenWhGLJAgak47Im6Vjenbr1uFUf%2BguxS%2Bbs1nsKoe5YDOhrXPMX4SiB0dL%2F0%2FbkY1Q60jaXdnKPmIQcfwtZfzbZ9Mu%2FMrYxWtZJUhGp5plpA%3D%3D
         * &trade_no=2020090322001477320501012225
         * &auth_app_id=2021000119602127
         * &version=1.0
         * &app_id=2021000119602127
         * &sign_type=RSA2
         * &seller_id=2088621957673428
         * &timestamp=2020-09-03+16%3A11%3A11
         * 2.插入数据库*/
        System.out.println("支付成功");
        String hoocTradeNo = request.getParameter("out_trade_no");
        String aliTradeNo = request.getParameter("trade_no");
        String totalPrice = request.getParameter("total_amount");

        String courseId = request.getParameter("passback_params");
        System.out.println("hoocTradeNo is : " + hoocTradeNo);
        System.out.println("aliTradeNo is : " + aliTradeNo);
        System.out.println("totalPrice is : " + totalPrice);
        System.out.println("courseId is : " + courseId);
        Object user = request.getSession().getAttribute(Constants.SESSION_KEY_LOGIN_USER);
        System.out.println("user is : " + user);
        response.sendRedirect("/hooc/views/hooc-user/courseVideo.html");
        return null;
    }

    @GetMapping("/info")
    @ApiOperation("根据用户id查询订单信息")
    public RespResult getOrderByUserId(Long userId) {
        System.out.println("into  /order/info .....");
        List<Order> orders = orderService.selectOrderByUserId(userId);
        return returnRespWithSuccess(orders);
    }

}
